package com.example.myapplication.tools;


import android.annotation.SuppressLint;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.myapplication.R;
import com.example.myapplication.WordApp;
import com.example.myapplication.model.Word;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

public class SQLiteHelper {

    private static SQLiteHelper mInstance;

    private SQLiteDatabase mDataBase;

    private SQLiteHelper()
    {}

    public static SQLiteHelper getInstance() {
        if(mInstance == null){
            mInstance = new SQLiteHelper();
        }
        return mInstance;
    }

    private void openDataBase() {
        if(mDataBase != null && mDataBase.isOpen()) {
            return;
        }
        InputStream ins = WordApp.AppCtx.getResources().openRawResource(R.raw.words);
        String dst = WordApp.AppCtx.getExternalFilesDir("").getAbsolutePath()+"/words.db";
        try {
            FileOutputStream fos = new FileOutputStream(dst);
            byte[] buf = new byte[ins.available()];
            while (true) {
                int length = ins.read(buf);
                if(length > 0) {
                    fos.write(buf,0,  length);
                } else {
                    break;
                }
            }
            fos.flush();
            fos.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        mDataBase = SQLiteDatabase.openDatabase(dst,null, SQLiteDatabase.OPEN_READONLY);
    }


    @SuppressLint("Range")
    public List<Word> query(String db, int s, int e) {
        List<Word> result = new ArrayList<>();
        String sql = "SELECT * FROM " + db + " WHERE id >= " + s + " and id <= " + e;
        openDataBase();
        Cursor cursor = mDataBase.rawQuery(sql, null);
        while (cursor.moveToNext()) {
            Word w = new Word();
            w.id = cursor.getInt(0);
            w.en = cursor.getString(cursor.getColumnIndex("en"));
            w.vt = cursor.getString(2);
            w.vi = cursor.getString(3);
            w.n = cursor.getString(4);
            w.adj = cursor.getString(5);
            w.adv = cursor.getString(6);
            w.conj = cursor.getString(7);
            w.prep = cursor.getString(8);
            w.pron = cursor.getString(9);
            w.art = cursor.getString(10);
            w.abbr = cursor.getString(11);
            w.other = cursor.getString(12);
            result.add(w);
        }
        return result;
    }

}
